package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.springboot.common.ResultVO;
import com.example.springboot.config.shiro.JWTToken;
import com.example.springboot.entity.User;
import com.example.springboot.service.UserService;
import com.example.springboot.util.RedisUtil;
import com.example.springboot.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String defaultLogin(){
        return "首页";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultVO login(@RequestBody User user){

        Subject subject = SecurityUtils.getSubject();
        JWTToken token = null;
        try {
            // 用户重新登入，根据用户名（用户名唯一），删除redis中存在的token
            redisUtil.del(RedisUtil.USER_TOKEN + user.getUsername());
            String tokenString = TokenUtil.getToken(user);
            token = new JWTToken(tokenString);
            subject.login(token);
        }catch (UnknownAccountException uae){
            log.error("uae", uae);
            return new ResultVO(200,"未知账号", null);
        }catch (IncorrectCredentialsException ice){
            log.error("ice", ice);
            return new ResultVO(200,"密码不正确", null);
        }catch (LockedAccountException lae){
            log.error("lae", lae);
            return new ResultVO(200,"账号已锁定", null);
        }catch (ExcessiveAttemptsException eae){
            log.error("eae", eae);
            return new ResultVO(200,"用户名或密码错误次数过多", null);
        }catch (AuthenticationException ae){
            log.error("ae", ae);
            return new ResultVO(200,"用户名或密码不正确", null);
        }
        if(subject.isAuthenticated()){
            return new ResultVO(200,"登录成功", token.getPrincipal());
        }else {
            token.clear();
            return new ResultVO(200,"登录失败", null);
        }
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(){
        return "hello world";
    }

    @RequestMapping(value = "/getUser")
    @RequiresPermissions("user:show")
    public ResultVO getUser(HttpServletRequest request){
        String token = request.getHeader("token");
        String username = TokenUtil.getUsername(token);
        QueryWrapper<User> queryWrapper = Wrappers.query();
        queryWrapper.eq("username", username);
        User userByUserName = userService.getOne(queryWrapper);
        return new ResultVO(200,"获取成功", userByUserName);
    }

    @RequestMapping(value = "/api/getToken", method = RequestMethod.GET)
    public ResultVO getToken(){
        User user = new User();
        user.setUsername("张三");
        user.setPassword("123456");
        String token = TokenUtil.getToken(user);
        return new ResultVO(200,"登录成功", token);
    }

    @RequestMapping(path = "front/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResultVO unauthorized() {
        return new ResultVO(401, "Unauthorized", null);
    }

}
